<?php

namespace App\Http\Controllers\App;
use Illuminate\Http\Request;
use App\Http\Controllers\Controller;
use App\Models\User;
use Crypt;
class LoginController extends Controller
{
    //
    
    protected function login(Request $request){
    	$code = $request->input('code');
		$json = $this->getopenid($code);
		$userinfo = json_decode($json);
		$user = User::where('openid',$userinfo->openid)->first();
		if(!$user){
			$user = new User;
			$user->openid = $userinfo->openid;
		}
		$user->token = md5($user->uid.time());
		$user->save();
		$_token = Crypt::encrypt(array(
			'uid'			=> $user->uid,
			'user_token'	=> $user->token
			));
		return response()->json([
			'code'	=> '00000',
			'msg'	=> 'ok',
			'data'	=> array(
				'user_token' => $_token
				)
			]);
    }
	
	/*
	 * 获取openid
	 * */
	protected function getopenid($code){
		$appid	= 'wxc313c63494a4f192';
		$secret = 'bf785d0da4709769ea60142119c507a7';
		$url = "https://api.weixin.qq.com/sns/jscode2session?appid={$appid}&secret={$secret}&js_code={$code}&grant_type=authorization_code";
		$res = file_get_contents($url);
		return $res;
	}
}
